package cn.easier.activity.console.utils;

import cn.easier.activity.console.params.MessagePostParams;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 邮短延迟任务类
 */
public class DelayMessage implements Delayed {

    private final long expire;
    private final MessagePostParams params;

    public DelayMessage(MessagePostParams params) {
        String time = params.getTime();
        Date date;
        try {
            date = DateUtils.parseDate(time, "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            date = new Date();
        }
        long targetTime = date.getTime();
        this.expire = Math.max(targetTime, System.currentTimeMillis());
        this.params = params;
    }

    public MessagePostParams getParams() {
        return params;
    }

    /**
     * 剩余时间=到期时间-当前时间
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 优先队列里面优先级规则
     */
    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }
}
